package org.example.datastructure.ch2;

public class dLinkList {
    int val;
    public dLinkList prev;
    public dLinkList next;
    public dLinkList(){
        this.val = 0;
        this.prev = null;
        this.next = null;
    }
    public dLinkList(int val) {
        this.val = val;
        this.prev = null;
        this.next = null;
    }
    public dLinkList(int val, dLinkList prev, dLinkList next) {
        this.val = val;
        this.prev = prev;
        this.next = next;
    }
    public dLinkList move(int i){
        dLinkList p = this;
        while(i-->0){
            p = p.next;
        }
        return p;
    }
    public dLinkList insert(dLinkList q, int val){
        dLinkList p = this;
        while(p.next!= null){
            p = p.next;
        }
        p.prev.next = q;
        p.prev = q;
        q.next = p;
        q.prev = p.prev;
        return q;
    }
    public dLinkList remove(int i){
        dLinkList p = move(i);
        p.prev.next = p.next;
        p.next.prev = p.prev;
        return p;
    }
    public int search(int v){
        dLinkList p = this;
        int i = 0;
        while(p!=null&&p.val!=v){
            p = p.next;
            i++;
        }
        if(p == null) return -1;
        return i;
    }
    public int visit(int i){
        return move(i).val;
    }
    public void reverse(){
        dLinkList p = this;
        while(p.next!=null){
            p = p.next;
        }
        while(p!=null){
            System.out.println(p.val);
            p = p.prev;
        }
    }

}
